package com.ry.thread;

import com.ry.request.InventoryRequest;
import com.ry.request.InventoryRequestQueue;
import java.util.concurrent.*;

/**
 * 库存处理线程池
 */
public class InventoryHandleThreadPool {

    /**
     * 线程池：10个核心线程
     */
    private ExecutorService threadPool = new ThreadPoolExecutor(10, 10,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>());


    public InventoryHandleThreadPool() {

        InventoryRequestQueue inventoryRequestQueue = InventoryRequestQueue.getInstance();

        // 初始化10个库存处理线程
        for (int i = 0; i < 10; i++) {
            // 初始化默认长度100的内存队列
            ArrayBlockingQueue<InventoryRequest> queue = new ArrayBlockingQueue<>(100);

            // 将内存队列添加到内存队列集合，用于后续内存队列的分发
            inventoryRequestQueue.add(queue);

            // 启动库存请求线程
            threadPool.submit(new InventoryHandleThread(queue));
        }

    }

    private static class Singleton {
        private static InventoryHandleThreadPool instance;

        static {
            instance = new InventoryHandleThreadPool();
        }

        public static InventoryHandleThreadPool getInstance(){
            return instance;
        }
    }

    /**
     * JVM机制去保证多线程并发安全
     *
     * 内部类的初始化，一定只会发生一次，不管多少个线程并发去初始化
     */
    public static InventoryHandleThreadPool getInstance(){
        return Singleton.getInstance();
    }



}
